//
//  ZXDownloadFile.m
//  ZXDownload
//
//  Created by xin on 2018/5/9.
//  Copyright © 2018年 魏鑫. All rights reserved.
//

#import "ZXDownloadFile.h"
#import "ZXDownloadSupportUtils.h"

@implementation ZXDownloadFile


- (instancetype)initWithURL:(nullable NSString *)url {
    if (self = [super init]) {
        self.fileURL = url;
        self.totalBytesExpectedToWrite = 1;
    }
    return self;
}

- (NSString *)filePath {
    NSString *path = [[ZXDownloadSupportUtils cacheFolder] stringByAppendingPathComponent:self.fileName];
    if (![path isEqualToString:_filePath]) {
        if (_filePath && ![[NSFileManager defaultManager] fileExistsAtPath:_filePath]) {
            NSString *dir = [_filePath stringByDeletingLastPathComponent];
            [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
            NSLog(@"filePath=%@",path);
        }
        _filePath = path;
    }
    return _filePath;
}

- (NSString *)fileName {
    if (_fileName == nil) {
        NSString *pathExtension = self.fileURL.pathExtension;
        if (pathExtension.length) {
            _fileName = [NSString stringWithFormat:@"%@.%@",[ZXDownloadSupportUtils getMD5String:self.fileURL],pathExtension];
        } else {
            _fileName = [ZXDownloadSupportUtils getMD5String:self.fileURL];
        }
    }
    return _fileName;
}

- (long long)totalBytesWritten {
    return [ZXDownloadSupportUtils fileSizeForPath:self.filePath];
}

- (NSProgress *)progress
{
    if (_progress == nil) {
        _progress = [[NSProgress alloc] initWithParent:nil userInfo:nil];
    }
    @try {
        _progress.totalUnitCount = self.totalBytesExpectedToWrite;
        _progress.completedUnitCount = self.totalBytesWritten;
    } @catch (NSException *exception) {
        
    }
    return _progress;
}

- (NSOutputStream *)stream {
    if (_stream == nil) {
        _stream = [NSOutputStream outputStreamToFileAtPath:self.filePath append:YES];
    }
    return _stream;
}

- (NSString *)formatByteCount:(long long)size
{
    NSString * speed = [NSByteCountFormatter stringFromByteCount:size countStyle:NSByteCountFormatterCountStyleFile];
    return speed ? speed : @"0";
}

- (NSString *)customFormatByteCount:(long long)size
{
    double convertedValue = size;
    int multiplyFactor = 0;
    NSArray *tokens = [NSArray arrayWithObjects:@"bytes",@"KB",@"MB",@"GB",@"TB",@"PB",@"EB",@"ZB",@"YB", nil];
    while (convertedValue > 1024) {
        convertedValue /= 1024;
        multiplyFactor++;
    }
    return [NSString stringWithFormat:@"%4.2f %@",convertedValue,[tokens objectAtIndex:multiplyFactor]];
    
}

- (NSDictionary *)fileInfo
{
    NSString *path = self.filePath;
    //通过NSFileManager获取文件的属性
    NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:NULL];
    NSLog(@"%@",attributes);
    return attributes;
    
//    //通过MDItem获取文件的属性
//    MDItemRef item = MDItemCreate(kCFAllocatorDefault, (__bridge CFStringRef)path);
//    CFArrayRef names = MDItemCopyAttributeNames(item);
//    attributes = (__bridge_transfer NSDictionary *)(MDItemCopyAttributes(item, names));
//    CFRelease(item);
//    NSLog(@"%@",attributes);
//    //通过NSURL获取文件属性
//    NSURL *fileUrl = [NSURL fileURLWithPath:path];
//    attributes = [fileUrl resourceValuesForKeys:[NSArray arrayWithObject:NSURLFileSizeKey] error:NULL];
//    NSLog(@"%@",attributes);
}

#pragma mark - NSCoding
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.fileURL forKey:NSStringFromSelector(@selector(fileURL))];
    [aCoder encodeObject:self.filePath forKey:NSStringFromSelector(@selector(filePath))];
    [aCoder encodeObject:self.fileName forKey:NSStringFromSelector(@selector(fileName))];
    [aCoder encodeObject:self.fileType forKey:NSStringFromSelector(@selector(fileType))];
    [aCoder encodeObject:@(self.totalBytesWritten) forKey:NSStringFromSelector(@selector(totalBytesWritten))];
    [aCoder encodeObject:@(self.totalBytesExpectedToWrite) forKey:NSStringFromSelector(@selector(totalBytesExpectedToWrite))];
    [aCoder encodeObject:@(self.state) forKey:NSStringFromSelector(@selector(state))];
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self) {
        self.fileURL = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(fileURL))];
        self.filePath = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(filePath))];
        self.fileName = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(fileName))];
        self.fileType = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(fileType))];
        self.totalBytesWritten = [[aDecoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(totalBytesWritten))] unsignedIntegerValue];
        self.totalBytesExpectedToWrite = [[aDecoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(totalBytesExpectedToWrite))] unsignedIntegerValue];
        self.state = [[aDecoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(state))] unsignedIntegerValue];
        
    }
    return self;
}

@end
